import java.io.IOException;
import java.net.*;
import java.util.Scanner;

// 构建客户端
/*public class UdpEchoClient {
    private DatagramSocket packet=null;
    private String ip;
    private int port;

    public UdpEchoClient( String  Ip  ,int port) throws SocketException {
        packet=new DatagramSocket();
        this.ip=Ip;
        this.port=port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner in=new Scanner(System.in);
        while(true){
            //1. 输入请求
            String request=in.next();

            //2. 将请求 发给 服务器
            DatagramPacket requestPocket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(ip),port);
            packet.send(requestPocket);

            //3. 收到 服务器的响应
            DatagramPacket respondPocket=new DatagramPacket(new byte[2048],2048);
            packet.receive(respondPocket);

            // 收到响应之后， 将 字节流转化为字符流
            String respond=new String(respondPocket.getData(),0,respondPocket.getLength());

            System.out.println(respond);

        }

    }


    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}*/



public class UdpEchoClient {
    private DatagramSocket socket=null;
    private String ip;
    private int port;

    public UdpEchoClient(String Ip,int port) throws SocketException {
        socket=new DatagramSocket();
        this.ip=Ip;
        this.port=port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！！");
        while(true) {

            // 发起请求
            Scanner in = new Scanner(System.in);
            String request = in.next();
            DatagramPacket requestPocket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(ip), port);

            socket.send(requestPocket);

            // 接收服务器的响应
            DatagramPacket respondPocket = new DatagramPacket(new byte[2048],2048);
            socket.receive(respondPocket);


            String respond = new String(respondPocket.getData(), 0, respondPocket.getLength());

            System.out.println(respond);
        }
    }


    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",1245);
        client.start();
    }
}
